<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>居民信息管理 - 智慧小区管理系统</title>
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css">
    <script src="../lib/jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style>
        body { padding: 24px; background: #f5f7fa; }
        .resident-toolbar { margin-bottom: 16px; }
        .layui-table th, .layui-table td { text-align: center; }
        .resident-image {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 4px;
            border: 1px solid #e6e6e6;
            cursor: pointer;
            transition: transform 0.2s;
        }
        .resident-image:hover {
            transform: scale(1.1);
        }
        .layui-table-cell {
            height: auto;
        }
    </style>
</head>
<body>

<div class="layui-card">
    <div class="layui-card-header" style="font-size:1.2em;font-weight:bold;">居民信息管理</div>
    <div class="layui-card-body">

        <!-- 搜索表单 -->
        <form class="layui-form resident-toolbar" id="searchForm">
            <div class="layui-inline">
                <input type="text" name="residentId" placeholder="居民ID" class="layui-input">
            </div>
            <div class="layui-inline">
                <input type="text" name="name" placeholder="姓名" class="layui-input">
            </div>
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="search"><i class="layui-icon layui-icon-search"></i> 查询</button>
            <button class="layui-btn layui-btn-primary" type="reset"><i class="layui-icon layui-icon-refresh"></i> 重置</button>
        </form>

        <!-- 工具栏 -->
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
            </div>
        </script>


        <!-- 数据表格 -->
        <table class="layui-table" id="residentTable" lay-filter="residentTableFilter"></table>

        <!-- 操作栏模板 -->
        <script type="text/html" id="tableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i> 编辑 </a>
            {{# if(!d.userId) { }}
            <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="addUser"><i class="layui-icon layui-icon-face-smile"></i> 添加为用户 </a>
            {{# } }}
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete"><i class="layui-icon layui-icon-delete"></i> 删除 </a>
        </script>

        <!-- 人脸信息图片列模板 -->
        <script type="text/html" id="imageTpl">
            {{# if(d.faceImageUrl) { }}
            <img src="{{d.faceImageUrl}}" class="resident-image" onerror="this.src='../images/default_picture.png'">
            {{# } else { }}
            <img src="../images/default_picture.png" class="resident-image">
            {{# } }}
        </script>

        <!-- 添加/编辑弹窗 -->
        <div id="edit" style="display: none; padding: 10px;">
            <form class="layui-form" id="formData" lay-filter="editForm">
                <!-- 隐藏字段 -->
                <input type="hidden" name="residentId">

                <!--<div>
                    <div class="layui-form-item" id="property-laylabel">
                        <label class="layui-form-label">居民ID</label>
                        <div class="layui-input-block">
                            <input type="number" name="residentId" placeholder="请输入居民ID" class="layui-input">
                        </div>
                    </div>
                </div>-->
                <div class="layui-form-item">
                    <label class="layui-form-label">姓名</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" required lay-verify="required" placeholder="请输入姓名" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">联系电话</label>
                    <div class="layui-input-block">
                        <input type="text" name="phoneNumber" required lay-verify="required|phone" placeholder="请输入联系电话" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">身份证号</label>
                    <div class="layui-input-block">
                        <input type="text" name="idCard" placeholder="请输入身份证号" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">性别</label>
                    <div class="layui-input-block">
                        <select name="gender" lay-verify="required">
                            <option value="">请选择性别</option>
                            <option value="1">男</option>
                            <option value="2">女</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">人脸信息图片</label>
                    <div class="layui-input-block">
                        <input type="file" id="imageUpload" accept="image/*">
                        <input type="hidden" name="faceImageUrl" id="faceImageUrl">
                        <img id="imagePreview" class="resident-image" style="display:none;">
                        <div class="layui-form-mid layui-word-aux">请上传商品图片，支持jpg/png等格式</div>
                    </div>
                </div>
                <!--                <div class="layui-form-item">-->
                <!--                    <label class="layui-form-label">人脸图片地址</label>-->
                <!--                    <div class="layui-input-block">-->
                <!--                        <input type="text" name="faceImageUrl" placeholder="请输入人脸图片地址" class="layui-input">-->
                <!--                    </div>-->
                <!--                </div>-->

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="residentFormSubmit">提交</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="../lib/layui-v2.6.3/layui.js"></script>
<script>
    layui.use(['table', 'form', 'layer', 'jquery'], function () {

        const table = layui.table;
        const form = layui.form;
        const layer = layui.layer;
        const $ = layui.jquery;
        // 全局设置ajax请求头
        $.ajaxSetup({
            beforeSend: function(xhr) {
                const data = JSON.parse(localStorage.getItem('user'));
                //输出token
                console.log(data.token);
                if (data.token) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
                }
            }
        });
        function randomUsername() {
            // 生成8位随机字母+数字
            const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
            let uname = '';
            for (let i = 0; i < 8; i++) {
                uname += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            return 'user_' + uname;
        }
        // 全局设置ajax请求头
        $.ajaxSetup({
            beforeSend: function(xhr) {
                const data = JSON.parse(localStorage.getItem('user'));
                //输出token
                console.log(data.token);
                if (data.token) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
                }
            }
        });

        let index;

        // 初始化表格
        table.render({
            elem: '#residentTable',
            url: '/resident/queryPage',
            method: 'get',
            page: true,
            parseData: function (res) {
                console.log('parseData:', res);  // 打印原始响应数据
                return {
                    code: res.code,
                    msg: res.message,
                    count: res.data.total,
                    data: res.data.list
                };
            },
            response: {
                statusName: 'code',
                statusCode: 0,
                msgName: 'message',
                countName: 'count',
                dataName: 'data'
            },
            toolbar: '#toolbarDemo',  // 确认这里正确指向工具栏模板
            cols: [[
                { field: 'residentId', title: '居民ID', width: 80},
                { field: 'name', title: '姓名'},
                { field: 'userId', title: '用户ID' , width: 80},
                { field: 'phoneNumber', title: '联系电话' , width: 120},
                { field: 'idCard', title: '身份证号' , width: 120},
                { field: 'gender', title: '性别',templet: function(d) {
                        return d.gender === 1 ? '男' : (d.gender === 2 ? '女' : '未知');
                    } , width: 80},
                { field: 'faceImageUrl', title: '人脸信息图片', templet:'#imageTpl'},
                { title: '操作', toolbar: '#tableBar', align: 'center' }
            ]]
        });

        // 监听工具栏事件
        table.on('toolbar(residentTableFilter)', function (obj) {
            if (obj.event === 'add') {// 打开添加弹窗
                form.val('editForm',{residentId: '', name:'',phoneNumber:'',idCard:'',gender:'',faceImageUrl:''});//清空表单
                index=layer.open({
                    title: '添加居民信息',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    content: $('#edit'),
                    area: ['500px', '600px'],

                });
                $(window).on('resize',function(){
                    layer.full(index);
                })
            }
        });

        // 监听行操作
        table.on('tool(residentTableFilter)', function (obj) {
            const data = obj.data;
            if (obj.event === 'edit') {
                // 编辑操作
                form.val('editForm',data);
                layer.open({
                    title: '编辑居民信息',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    content: $('#edit'),
                    area: ['500px', '600px'],

                });
                $(window).on('resize',function(){
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                // 删除操作
                layer.confirm('确定删除改居民信息吗?', function (index) {
                    $.post('/resident/delete' , {id: data.residentId}, function (res) {
                        if (res.code === 0) {
                            layer.msg('删除成功');
                            obj.del();
                        } else {
                            layer.msg('删除失败:' + res.message);
                        }
                    })
                    layer.close(index);
                })
            }else if (obj.event === 'addUser') {
                // 获取居民信息
                var resident = obj.data;
                var username = randomUsername();
                var password = '12345678';
                var avatar = '/images/default_avatar.png';
                var roleId = 1; // 用户
                var mobile = resident.phoneNumber || '';
                var email = resident.email && resident.email.trim() !== '' ? resident.email : (mobile + '@qq.com');
                var status = 1; // 启用

                // 组装表单数据
                var formData = {
                    username: username,
                    password: password,
                    avatar: avatar,
                    roleId: roleId,
                    mobile: mobile,
                    email: email,
                    status: status,
                    residentId: resident.residentId
                };

                // 调用后端接口（表单格式）
                $.ajax({
                    url: '/resident/setUser',
                    type: 'POST',
                    data: formData,
                    success: function(res) {
                        if(res.code === 0){
                            layer.alert(
                                '<div style="text-align:left;">' +
                                '<b>用户创建成功！</b><br>' +
                                '用户名：' + username + '<br>' +
                                '初始密码：' + password + '<br>' +
                                '手机号：' + mobile + '<br>' +
                                '邮箱：' + email + '<br>' +
                                '角色：用户<br>' +
                                '状态：启用<br>' +
                                '</div>',
                                {title: '新用户信息'}
                            );
                        }else{
                            layer.msg('添加失败：' + (res.msg || '未知错误'), {icon:2});
                        }
                    },
                    error: function(){
                        layer.msg('请求失败，请稍后重试', {icon:2});
                    }
                });
            }
        });

        // 提交添加/编辑表单
        form.on('submit(residentFormSubmit)', function (data) {
            var field = data.field; // 获取表单字段
            var url = field.residentId ? '/resident/update' : '/resident/add';
            $.post(url, field, function (res) {
                if (res.code === 0) {
                    layer.msg(field.residentId ? '更新成功' : '添加成功');
                    table.reload('residentTable'); // 刷新表格
                    layer.close(index); // 关闭弹层
                } else {
                    layer.msg(field.residentId ? '更新失败' : '添加失败:' + res.message);
                }
            });
            return false; // 阻止表单默认提交行为
        });

        // 查询按钮点击事件
        form.on('submit(search)', function (data) {
            const field = data.field;
            table.reload('residentTable', {
                where: field, // 设置查询参数
                page: { curr: 1 } // 重置分页到第一页
            });
            return false; // 阻止表单默认提交行为
        });
        // 重置按钮点击事件
        $(document).on('click', '.layui-btn-primary[type="reset"]', function () {
            $('#searchForm')[0].reset();
            form.render();
            table.reload('residentTable', {
                where: {},
                page: { curr: 1 }
            });
            return false;
        });

        // 图片上传并预览
        $('body').on('change', '#imageUpload', function() {
            var file = this.files[0];
            if (!file) return;
            var formData = new FormData();
            formData.append('file', file);

            layer.msg('图片上传中...', {icon: 16, shade: 0.2, time: 0});
            $.ajax({
                url: '/oss/upload',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(res) {
                    layer.closeAll('loading');
                    if (res.code === 0) {
                        $('#imagePreview').attr('src', res.data).show();
                        $('#faceImageUrl').val(res.data);
                        layer.msg('图片上传成功');
                    } else {
                        layer.msg('图片上传失败: ' + res.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.closeAll('loading');
                    layer.msg('图片上传失败', {icon: 2});
                }
            });
        });

        // 表格中图片点击预览
        $(document).on('click', '.resident-image', function() {
            var src = $(this).attr('src');
            if (src && src !== '../images/default_picture.png') {
                layer.photos({
                    photos: {
                        "title": "商品图片预览",
                        "data": [{
                            "src": src
                        }]
                    }
                });
            }
        });
    });
</script>
</body>
</html>
